package com.yonyou.brigade.third_parties.tujia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.tujia.service.ITuJiaSSOService;
import com.yonyou.brigade.third_parties.tujia.util.TuJiaUtils;
import com.yonyou.ybzboot.starter.common.cipher.SHAUtil;
import com.yonyou.ybzboot.starter.common.cipher.SHAUtil.*;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 途家单点登录,返回URL如下所示
 * https://go.tujia.com/4011?code=yongyouapph5&mobile=13000000000&uid=123456&timestamp=1511340950&signature=740c248b9e6296afe48ac3995f5f1b7b
 *
 * @Auther: kfw
 * @Date: 2018/8/23 14:24
 */
@Service
public class TujiaSSOServiceImpl implements ITuJiaSSOService {
    @Value("${tujia.url}")
    private String baseUrl;
    @Value("${tujia.code}")
    private String tujiaCode;
    @Value("${tujia.secret}")
    private String tujiaSecret;
    @Value("${tujia.refurl}")
    private String refUrl;
    @Autowired
    private PropUtil propUtil;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;


    private Logger logger=LoggerFactory.getLogger(TujiaSSOServiceImpl.class);

//
//    /**
//     * 获取登录url
//     * @param tenant
//     * @param org
//     * @param phone
//     * @param pageType
//     * @param pcOrH5
//     * @param jsonExt
//     * @return
//     */
//     public  String loginUrl(String tenant, String org, String phone, String pageType, String pcOrH5, String jsonExt)
//     {
//         String resultUrl="";
//         UcUserDto ucUserDto= userCenterService.getCompleteUcUserDtoByPhone(phone,tenant);
//         BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant,org,ChannelEnum.TUJIA.getName());
//         String curBaseUrl=baseUrl;
//         String curTuJiaCode=tujiaCode;
//         String curTuJiaSecret=tujiaSecret;
//         if(ucUserDto==null||briChannel==null)
//        {
//            resultUrl = propUtil.getNO_ACCESS_URL();
//            return resultUrl;
//        }
//        else
//        {
//            if(briChannel.getConfig()!=null)
//            {
//                JSONObject jsonObject=JSONObject.parseObject(briChannel.getConfig());
//                if(jsonObject.containsKey("baseUrl")) {
//                    curBaseUrl = jsonObject.getString("baseUrl");
//                }
//                if(jsonObject.containsKey("tujiaCode"))
//                {
//                    curTuJiaCode=jsonObject.getString("tujiaCode");
//                }
//                if(jsonObject.containsKey("tujiaSecret"))
//                {
//                    curTuJiaSecret=jsonObject.getString("tujiaSecret");
//                }
//
//            }
//            try {
//                long timestamp = System.currentTimeMillis();
//                timestamp = timestamp / 1000;
//                String signature = SHAUtil.getMD5(phone + timestamp + curTuJiaSecret);
//                StringBuilder sburl = new StringBuilder();
//                sburl.append(curBaseUrl);
//                sburl.append("?channelCode=");
//                sburl.append(curTuJiaCode);
//                sburl.append("&mobile=");
//                sburl.append(phone);
//                sburl.append("&uid=");
//                sburl.append(tenant+"_"+ucUserDto.getPersonCode());//途家的唯一ID用租户_用户编码
//                sburl.append("&timestamp=");
//                sburl.append(timestamp);
//                sburl.append("&signature=");
//                sburl.append(signature);
//                resultUrl=sburl.toString();
//            }
//            catch (Exception e)
//            {
//                throw  new BusinessException("获取途家地址失败");
//            }
//        }
//        return  resultUrl;
//     }

     public String getSSOUrl(String tenant,String mobile)
     {
         StringBuilder urlBuilder=new StringBuilder();
         long timeStamp=System.currentTimeMillis()*1000;

         String memberLevel=TuJiaUtils.MEMBERLEVEL;
         UcUserDto ucUserDto=userCenterService.getCompleteUcUserDtoByPhone(mobile,tenant);
         if(ucUserDto == null) {
             logger.error("从用户中心获取不到用户"+mobile+"("+tenant+")");
             return propUtil.getNO_ACCESS_URL();
         }
         else
         {
             String userid=tenant+"_"+ucUserDto.getPersonCode();
             try
             {
                 String aesMobile=TuJiaUtils.encryptData(mobile);
                 String aesUid=TuJiaUtils.encryptData(userid);
                 String sig=TuJiaUtils.encryptMD5(userid+memberLevel+tujiaCode+timeStamp+TuJiaUtils.KEY,true);
                 urlBuilder.append(baseUrl);
                 urlBuilder.append("?mobile=");
                 urlBuilder.append(aesMobile);
                 urlBuilder.append("&uid=");
                 urlBuilder.append(aesUid);
                 urlBuilder.append("&timestamp=");
                 urlBuilder.append(timeStamp);
                 urlBuilder.append("&memberlevel=");
                 urlBuilder.append(TuJiaUtils.MEMBERLEVEL);
                 urlBuilder.append("&signature=");
                 urlBuilder.append(sig);
                 urlBuilder.append("&code=");
                 urlBuilder.append(tujiaCode);
                 urlBuilder.append("&refurl=");
                 urlBuilder.append(refUrl);
             }
             catch (Exception e)
             {
                 logger.error(e.getMessage());
             }

             logger.info("tujialogin:"+userid+memberLevel+tujiaCode+timeStamp+TuJiaUtils.KEY+":"+urlBuilder.toString());
            return  urlBuilder.toString();
         }
//         https://hes.tujia.com/page/1?mobile=XXXXXX&uid=1234&timestamp=1526636075000&memberlevel=X&signature=9b6a2e2406c193e01acb6a2ab9235184&code=XXX&refurl=https%3A%2F%2Fwww.baidu.com%2F
     }

}
